var stats = new Stats(),
    sds = stats.domElement.style;
sds.position = 'absolute';
sds.top = '0px';
sds.right = '0px';
document.body.appendChild(stats.domElement);

var c = document.getElementById('c'), cBuffer = document.createElement('canvas'),
    ctx = c.getContext('2d'), ctxBuffer = cBuffer.getContext('2d'),
    pt;

/* ===================================================== */
/* 主类 */
/* ===================================================== */
function ParticleText() {
    this.text = 'Hello';
    this.particles = [];
    this.newParticles = [];
    this.step = 5;
    this.fontsize = 0;
    this.data32;
    this.isFirst = true;
    pt = this;
    return pt;
}
ParticleText.prototype = {
    setText: function(text) {
        this.text = text || 'Hello';
        this.draw();
    },
    setFontsize: function(value) {
        this.fontsize = value || 0;
        this.step = Math.floor(this.fontsize / 25);
    },
    draw: function() {
        var x, y, color;
        //在内存绘制文字，获取imageData
        ctxBuffer.save();
        ctxBuffer.clearRect(0, 0, cBuffer.width, cBuffer.height);
        ctxBuffer.font = `${this.fontsize}px Arial`;
        ctxBuffer.textAlign = 'center';
        ctxBuffer.fillStyle = '#fff';
        ctxBuffer.fillText(this.text, cBuffer.width / 2, cBuffer.height / 2);
        ctxBuffer.restore();

        var data = ctxBuffer.getImageData(0, 0, cBuffer.width, cBuffer.height).data;
        var data32 = new Uint32Array(data.buffer);

        if(this.particles.length != 0) {
            this.newParticles = [];
            for(x = 0; x < cBuffer.width; x += this.step) {
                for(y = 0; y < cBuffer.height; y += this.step) {
                    color = data32[y * cBuffer.width + x];
                    if(color != 0) {
                        this.newParticles.push(new Particle(
                            x, 
                            y, 
                            Math.random() * this.step / 3));
                    }
                }
            }
            if(this.newParticles.length > this.particles.length) {
                for(x = this.particles.length; x < this.newParticles.length; x += 1) {
                    this.particles.push(new Particle(
                        this.newParticles[x].x,
                        this.newParticles[x].y,
                        this.newParticles[x].radius
                    ))
                }
            } else if (this.newParticles.length < this.particles.length) {
                this.particles.splice(this.newParticles.length);
            }
            //用tween驱动更新
            for(var i = 0; i < this.particles.length; i += 1) {
                (function(i, self){
                    self.particles[i].tween = new TWEEN.Tween(self.particles[i]).to({
                        x: self.newParticles[i].x,
                        y: self.newParticles[i].y
                    }, 400)
                    .easing(TWEEN.Easing.Quartic.Out)
                    .onUpdate(function(obj) {
                        self.particles[i].update(ctx, obj);
                    })
                    .start();
                })(i, this)
            }
        } else {
            for(x = 0; x < cBuffer.width; x += this.step) {
                for(y = 0; y < cBuffer.height; y += this.step) {
                    color = data32[y * cBuffer.width + x];
                    if(color != 0) {
                        this.particles.push(new Particle(
                            x, 
                            y, 
                            Math.random() * this.step / 3));
                    }
                }
            }
        }
    }
}

/* ===================================================== */
/* 粒子类 */
/* ===================================================== */
function Particle(x, y, radius) {
    Vector.call(this, x, y);
    this.radius = radius || 3;
    this.v = 1;
    this.a = 5;
    this.tween = null;
}
Particle.prototype = (function(o){
    var s = new Vector(0, 0), p;
    for(p in 0) s[p] = o[p];
    return s;
})(Vector.prototype);
Particle.prototype.update = function(ctx, obj) {
    if(pt.newParticles.length != 0) {
        if(obj) {
            this.x = obj.x;
            this.y = obj.y;
        }
    }
    this.draw(ctx, pt);
};
Particle.prototype.draw = function(ctx, pt) {
    ctx.save();
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
}

pt = new ParticleText();

//处理canvas宽高
var input = document.getElementById('input');
function handleResize() {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
    cBuffer.width = window.innerWidth * window.devicePixelRatio;
    cBuffer.height = window.innerHeight * window.devicePixelRatio;
    pt.setFontsize(Math.min(c.width, c.height) / 2.5);
}
function handleInputBlur(init) {
    if(typeof init === 'object') {
        if(this.value) {
            pt.setText(this.value);
        }
    } else {
        pt.setText(init);
    }
}
function handleKeyup(e) {
    var event = e || window.event;
    if(event.keyCode === 13 && input.value) {
        input.blur();
    }
}
window.addEventListener('resize', handleResize, false);
handleResize();
input.addEventListener('blur', handleInputBlur, false);
document.addEventListener('keyup', handleKeyup, false);
handleInputBlur('Hello');

//动画函数
(function animate(){
    var curlist
    ctx.fillStyle = '#1c1c1c';
    ctx.fillRect(0, 0, c.width, c.height);

    // if(pt.newParticles.length === 0) {
        for(var i = 0; i < pt.particles.length; i += 1) {
            pt.particles[i].update(ctx);
        }
    // }
    
    requestAnimationFrame(animate);
    TWEEN.update();
    stats.update();
})()

